<?php

declare(strict_types=1);

namespace app\service\user\login;

use app\model\UserAuth;

class PhonePassword implements LoginInterface
{
    public function login(array $credentials): array
    {
        $phone = $credentials['phone'] ?? '';
        $password = $credentials['password'] ?? '';

        $userAuth = UserAuth::where('identity_type', UserAuth::TYPE_PASSWORD)
            ->where('identifier', $phone)
            ->find();

        if (!$userAuth) {
            return [
                'status' => 'error',
                'msg' => '用户不存在'
            ];
        }

        if (!$userAuth->credential || !password_verify($password, $userAuth->credential)) {
            return ['status' => 'error', 'msg' => '密码错误'];
        }

        $userAuth->user()->update(['last_login_time' => date('Y-m-d H:i:s')]);
        return ['status' => 'success', 'user' => $userAuth->user];
    }

    public function getIdentifier(): string
    {
        return 'phone_password';
    }
}
